<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" width="55%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="120px">

      <el-card class="content-card">
        <el-descriptions :column="responsiveState.column" title="结算信息">
          <el-descriptions-item :width="itemWidth" label="记录编号：">
            <span>{{ formData.id }}</span>
          </el-descriptions-item>
          <el-descriptions-item :width="itemWidth" label="结算状态：">
            <DictTag v-model="formData.status" :circle="false" dict-type="merchant_settlement_status"/>
          </el-descriptions-item>
          <el-descriptions-item :width="itemWidth" label="结算金额：">
            <span style="font-weight: 500;color: var(--el-color-primary);font-size: 16px">{{ toDecimal(formData.amount, 4) }}</span>
          </el-descriptions-item>

          <el-descriptions-item :width="itemWidth" label="商户编号：">
            <span>{{ formData.shop_id }}</span>
          </el-descriptions-item>
          <el-descriptions-item :width="itemWidth" label="商户类型：">
            <DictTag v-model="formData.shop_type" :circle="false" dict-type="shop_type"/>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-divider border-style="dashed"/>

      <el-card class="content-card">
        <el-descriptions :column="1" title="结算账户">
          <el-descriptions-item :width="itemWidth" label="类型：">
            <DictTag v-model="formData.account_type" :circle="false" dict-type="settlement_account_type"/>
          </el-descriptions-item>
          <el-descriptions-item :width="itemWidth" label="账户名：">
            <span>{{ formData.account_name || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item :width="itemWidth" label="账户号：">
            <span>{{ formData.account_no || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item :width="itemWidth" label="开户银行：">
            <span>{{ formData.bank_name || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item :width="itemWidth" label="开户支行：">
            <span>{{ formData.branch_name || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-divider border-style="dashed"/>

      <el-card class="content-card">
        <el-descriptions :column="2" title="付款信息">
          <el-descriptions-item :width="itemWidth" label="付款凭证：">
            <UploadImage style="display: inline-block" v-model="formData.payment_voucher" :disabled="readonly" :show-delete="true" :show-tip="false"/>
          </el-descriptions-item>

          <el-descriptions-item :width="itemWidth" label="打款时间：" v-if="formData.status == 100">
            <span>{{ formData.payment_time || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <template v-if="formData.status == 110">
        <el-divider border-style="dashed"/>

        <el-card class="content-card">
          <el-descriptions :column="2" title="驳回信息">
            <el-descriptions-item :width="itemWidth" label="驳回时间：">
              <span>{{ formData.audit_time || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item :width="itemWidth" label="驳回原因：">
              <span>{{ formData.audit_reason || '-' }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </template>

    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <template v-if="!readonly && hasPermission('merchant:settlement:operations')">
          <el-button v-if="formData.status == 10" :loading="dataLoading" type="info" @click="onSubmitForm(20)">结算处理</el-button>
          <el-button v-if="formData.status == 10 || formData.status == 20" :loading="dataLoading" type="danger" @click="onSubmitForm(100)">结算完成</el-button>
          <el-button v-if="formData.status == 10 || formData.status == 20" :loading="dataLoading" type="primary" @click="dataFormSubmitRefuse()">驳回申请</el-button>
        </template>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElMessageBox, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { MerchantSettlement, merchantSettlementAction, merchantSettlementInfo } from '@/api/api-merchant.ts';
import { DictTag } from '@/components/dict-tag';
import { useResponsiveState } from '@/hooks/use-responsive-state.ts';
import { toDecimal } from '@/utils';
import { UploadImage } from '@/components/upload';
import { hasPermission } from '@/utils/permission.ts';

defineOptions({name: 'merchant-settlement-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogIconMap} = useDialog(false);
const dialogModeMap = {0: '查看', 2: '操作'};

/** 默认表单数据 */
const defaultForm: MerchantSettlement = <MerchantSettlement>{};
// 表单数据
const formData = ref({...defaultForm});
// 表单验证规则
const formRules = reactive<FormRules>({});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '商户结算';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await merchantSettlementInfo(id);
      formData.value = data;
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async (auditStatus: number) => {
  ElMessageBox.confirm('是否确认进行此操作?', {
    title: '提示',
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    if (auditStatus === 100 && !formData.value.payment_voucher) {
      ElMessage({type: 'error', message: '请上传打款凭证图片',});
      return
    }

    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    let params = {
      id: formData.value.id,
      status: auditStatus,
      payment_voucher: formData.value.payment_voucher
    }
    // 提交数据
    merchantSettlementAction(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

const dataFormSubmitRefuse = async () => {
  ElMessageBox.prompt('是否拒绝当前记录的结算申请？', {
    title: '驳回申请',
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入驳回原因',
  }).then(({value}) => {
    // 结算状态 10:待审核 20:结算中 100:已结算 110:已驳回
    if (!value) {
      ElMessage({type: 'error', message: '请输入驳回原因',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    let params = {
      id: formData.value.id,
      status: 110,
      audit_reason: value
    }
    // 提交数据
    merchantSettlementAction(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())
  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

const itemWidth = ref('130px')
const responsiveState = useResponsiveState(
    {
      ['lg']: {column: 3},
      ['sm']: {column: 2},
      ['xs']: {column: 1},
    },
    {column: 3,},
);

</script>

<style lang="scss" scoped>
:deep() {
  .el-descriptions__label {
    margin-right: 0;
    display: inline-block;
    min-width: 72px;
    vertical-align: top;
  }

  .el-descriptions__cell {
    vertical-align: top;
    font-size: 13px !important;
  }

  .el-divider--horizontal {
    margin: 8px 0;
  }

  .el-descriptions__body .el-descriptions__table:not(.is-bordered) .el-descriptions__cell {
    padding-bottom: 6px;
  }
}
</style>
